package cn.zyl.quartz.controller;

import org.quartz.JobKey;
import org.quartz.Scheduler;
import org.quartz.Trigger;
import org.quartz.TriggerKey;
import org.quartz.impl.jdbcjobstore.TriggerStatus;
import org.quartz.impl.matchers.GroupMatcher;
import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Date;
import java.util.List;

@WebServlet("/GetAllJobServlet")
public class GetAllJobServlet extends HttpServlet{

    private static AbstractApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
    private static Scheduler scheduler = (Scheduler) context.getBean("scheduler");

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
            try {
                Scheduler scheduler = getScheduler();
                for (String groupName : scheduler.getJobGroupNames()) {
                    for (JobKey jobKey : scheduler.getJobKeys(GroupMatcher.jobGroupEquals(groupName))) {
                        String jobName = jobKey.getName();
                        String jobGroup = jobKey.getGroup();
                        //get job's trigger
                        List<Trigger> triggers = (List<Trigger>) scheduler.getTriggersOfJob(jobKey);
                        //下次点火时间
                        Date nextFireTime = triggers.get(0).getNextFireTime();
                        //当前状态
                        TriggerKey triggerKey = TriggerKey.triggerKey(jobKey.getName(), jobKey.getGroup());
                        Trigger.TriggerState triggerState = scheduler.getTriggerState(triggerKey);

                        System.out.println("[jobName] : " + jobName + " [groupName] : "
                                + jobGroup + " - " + nextFireTime + "  [state] : " + triggerState.toString() );
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
    }

    public static Scheduler getScheduler() {
        return scheduler;
    }
}
